package angle.controller;

import angle.pojo.Provider;
import angle.pojo.User;
import angle.service.bill.BillService;
import angle.service.provider.ProviderService;
import angle.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/pro")
public class ProviderController {

    @Autowired
    private ProviderService providerService;

    @Autowired
    private BillService billService;

    /*实现用户列表页面,动态实现用户删除*/
    @RequestMapping("/prolist")
    public ModelAndView providerList(HttpServletRequest req, HttpServletResponse resp) {
        ModelAndView mav = new ModelAndView();
        //从前端获取数据
        String method = req.getParameter("method");
        Map<String, Object> map = new HashMap<String, Object>();
        if (method.equals("query") && method != null) {
            //获取查询栏对数据
            String queryProCode = req.getParameter("queryProCode");
            String queryProName = req.getParameter("queryProName");
            String pageIndex = req.getParameter("pageIndex");
            //设置每页到显示个数
            int pageSize = 5;
            //设置当前页面值
            int currentPageNo = 1;
            //判断防止传入空字符串导致动态sql错误拼接从而查询失败
            //并将其添加到查询需要对map中
            if (queryProCode != null && !queryProCode.equals("")) {
                map.put("proCode", queryProCode);
            } else {
                map.put("proCode", null);
            }
            if (queryProName != null && !queryProName.equals("")) {
                map.put("proName", queryProName);
            } else {
                map.put("proName", null);
            }
            //判断页面到当前页，保证页面数不为空
            if (pageIndex != null) {
                try {
                    currentPageNo = Integer.parseInt(pageIndex);
                } catch (Exception e) {
                    mav.setViewName("redirect:/error.jsp");
                    return mav;
                }
            }
            map.put("currentPageNo", (currentPageNo - 1) * pageSize);
            map.put("pageSize", pageSize);
            //获取供应商用户总数
            int totalCount = providerService.queryProCount(map);
            //分页实现
            PageSupport pageSupport = new PageSupport();
            pageSupport.setCurrentPageNo(currentPageNo);
            pageSupport.setPageSize(pageSize);
            pageSupport.setTotalCount(totalCount);
            //获取页面总数
            int totalPageCount = pageSupport.getTotalPageCount();
            //控制首尾页跳转
            if (currentPageNo < 1) {
                currentPageNo = 1;
            } else if (currentPageNo > totalPageCount) {
                currentPageNo = totalPageCount;
            }
            //获取供应商列表
            List<Provider> proList = providerService.getProList(map);
            //给试图层传递参数
            mav.addObject("providerList", proList);
            mav.addObject("totalCount", totalCount);
            mav.addObject("currentPageNo", currentPageNo);
            mav.addObject("totalPageCount", totalPageCount);
            //保证再点击查询之后，查询框中到内容还在
            mav.addObject("queryProCode", queryProCode);
            mav.addObject("queryProName", queryProName);
            mav.setViewName("providerlist");
        }
        /*ajax动态删除用户实现（待完善）*/
        else if (method.equals("delprovider") && method != null) {
            String id = req.getParameter("proid");
            Integer delId = 0;
            try {
                delId = Integer.parseInt(id);
            } catch (Exception e) {
                delId = 0;
            }
            //获取当前供应商的订单数量
            int totalCount = billService.getBillCountByProId(delId);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            //如果选中的id不为正，则错误
            if (delId <= 0) {
                resultMap.put("delResult", "notexist");
            } else if (totalCount == 0) {
                if (providerService.deleteProById(delId) > 0) {
                    resultMap.put("delResult", "true");
                } else {
                    resultMap.put("delResult", "false");
                }
            } else {
                resultMap.put("delResult", totalCount);
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                resp.setContentType("application/json;charset=utf-8");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = resp.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
            mav.setViewName("userlist");
        }
        return mav;
    }

    /*跳转到用户添加界面*/
    @RequestMapping("/toproadd")
    public String toProviderAdd() {
        return "provideradd";
    }

    /*实现供应商添加*/
    @RequestMapping("/proadd")
    public ModelAndView providerAdd(Provider provider, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        String method = request.getParameter("method");
        //当method为add时，代表全部输入合法，成功添加
        if (method.equals("add") && method != null) {
            provider.setCreationDate(new Date());
            provider.setCreatedBy(((User) request.getSession().getAttribute("user")).getId());
            int flag = 0;
            flag = providerService.proAdd(provider);
            if (flag > 0) {
                mav.setViewName("redirect:/pro/prolist?method=query");
            } else {
                mav.setViewName("provideradd");
            }
        }
        //ajax动态验证供应商编码proCode是否已经存在
        else if (method.equals("pcexist") && method != null) {
            //判断供应商编码是否可用
            String proCode = request.getParameter("proCode");
            //用于存放对proCode判断对结果
            Map<String, String> resultMap = new HashMap<String, String>();
            //判断proCode是否为空
            if (StringUtils.isNullOrEmpty(proCode) || proCode == "") {
                resultMap.put("proCode", "empty");
            } else {
                Provider provider1 = new Provider();
                provider1.setProCode(proCode);
                provider1 = providerService.queryProNoLike(provider1);
                if (null != provider1) {
                    resultMap.put("proCode", "exist");
                } else {
                    resultMap.put("proCode", "notexist");
                }
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                response.setContentType("application/json");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = response.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //ajax动态验证供应商名称proName是否已经存在
        else if (method.equals("pnexist") && method != null) {
            //判断供应商名称是否可用
            String proName = request.getParameter("proName");
            //用于存放对proName判断的结果
            Map<String, String> resultMap = new HashMap<String, String>();
            //判断proName是否为空
            if (StringUtils.isNullOrEmpty(proName) || proName == "") {
                resultMap.put("proName", "empty");
            } else {
                Provider provider1 = new Provider();
                provider1.setProName(proName);
                provider1 = providerService.queryProNoLike(provider1);
                if (null != provider1) {
                    resultMap.put("proName", "exist");
                } else {
                    resultMap.put("proName", "notexist");
                }
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                response.setContentType("application/json");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = response.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mav;
    }

    /*实现供应商查看详情*/
    @RequestMapping("/proview")
    public ModelAndView providerView(int proid) {
        ModelAndView mav = new ModelAndView();
        Provider provider = new Provider();
        //根据id查询出当前选中的供应商
        provider.setId(proid);
        provider = providerService.queryProById(provider);
        //将数据传入前端
        mav.addObject("provider", provider);
        mav.setViewName("providerview");
        return mav;
    }

    /*跳转到供应商修改页面*/
    @RequestMapping("/topromodify")
    public ModelAndView toProviderModify(int proid) {
        ModelAndView mav = new ModelAndView();
        Provider provider = new Provider();
        //根据id查询出当前选中的供应商
        provider.setId(proid);
        provider = providerService.queryProById(provider);
        //将数据传入前端
        mav.addObject("provider", provider);
        mav.setViewName("providermodify");
        return mav;
    }

    /*实现供应商修改*/
    @RequestMapping("/promodify")
    public ModelAndView providerModify(Provider provider, HttpServletRequest req) {
        ModelAndView mav = new ModelAndView();
        //因为code和name栏设置为disable，所以要将其手动注入对象属性中
        provider.setProCode(req.getParameter("proCode"));
        provider.setProName(req.getParameter("proName"));
        //将修改者和修改时间注入对象属性中
        provider.setModifyBy(((User) req.getSession().getAttribute("user")).getId());
        provider.setModifyDate(new Date());
        int flag = providerService.modifyProById(provider);
        if (flag > 0) {
            mav.setViewName("redirect:/pro/prolist?method=query");
        } else {
            mav.setViewName("redirect:/pro/topromodify");
        }
        return mav;
    }
}
